package com.itheima.filter;



import com.itheima.util.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.io.IOException;


@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转ServletRequest servletRequest, ServletResponse servletResponse,
        //转成HttpServletRequest HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取url
        String requestURL = request.getRequestURL().toString();
        //判断url是否包含login
        if(requestURL.contains("login")){
            log.info("登录操作，放行");
            filterChain.doFilter(servletRequest ,servletResponse);
            return;
        }
        //判断有没有令牌
        String token = request.getHeader("token");
        if(!StringUtils.hasLength(token)){
            log.info("没有令牌不得入内");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
           /* Result notJwt = Result.error("NOT_LOGIN");
            String string = JSONObject.toJSONString(notJwt);
            response.getWriter().write(string);*/
            return;
        }
        //有令牌就解析令牌，如果报错就是解析令牌失败
        try {
            JwtUtil.ParseTwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //放行
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest ,servletResponse);
    }

}
